package com.pb.camera.jph.activity;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.util.Log;

import com.pb.camera.application.App;
import com.pb.camera.utils.Logger;
import com.pb.camera.utils.TaskHelper;
import com.pb.camera.work.ControlTask;

public class WifiAdmin {
    private static final String TAG = "WifiAdmin";
    // 定义WifiManager对象
    private WifiManager mWifiManager;
    // 定义WifiInfo对象  
    private WifiInfo mWifiInfo;
    // 扫描出的网络连接列表  
    private List<ScanResult> mWifiList;
    // 网络连接列表  
    private List<WifiConfiguration> mWifiConfiguration;
    // 定义一个WifiLock  
    WifiLock mWifiLock;

    public WifiAdmin(Context context) {

        // 取得WifiManager对象
        mWifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    //构造函数
    public WifiAdmin() {

        // 取得WifiManager对象  
        mWifiManager = (WifiManager) App.getInstance()
                .getSystemService(Context.WIFI_SERVICE);
        // 取得WifiInfo对象  
        mWifiInfo = mWifiManager.getConnectionInfo();
    }

    //获取wifi 名字的集合
    public List<String> getWifiNames() {
        List<String> wifiNameList = new ArrayList<String>();
        if (mWifiList.size() > 0) {
            for (ScanResult scanResult : mWifiList) {
                wifiNameList.add(scanResult.SSID);
            }
        }
        return wifiNameList;
    }

    // 打开WIFI  
    public void openWifi() {
        if (!mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(true);
        }
    }

    // 关闭WIFI  
    public void closeWifi() {
        if (mWifiManager.isWifiEnabled()) {
            mWifiManager.setWifiEnabled(false);
        }
    }

    // 检查当前WIFI状态  
    public int checkState() {
        return mWifiManager.getWifiState();
    }

    // 锁定WifiLock  
    public void acquireWifiLock() {
        mWifiLock.acquire();
    }

    // 解锁WifiLock  
    public void releaseWifiLock() {
        // 判断时候锁定  
        if (mWifiLock.isHeld()) {
            mWifiLock.acquire();
        }
    }

    // 创建一个WifiLock  
    public void creatWifiLock() {
        mWifiLock = mWifiManager.createWifiLock("Test");
    }

    // 得到配置好的网络  
    public List<WifiConfiguration> getConfiguration() {
        return mWifiConfiguration;
    }

    // 指定配置好的网络进行连接  
    public boolean connectConfiguration(int wifiId) {
        // 索引大于配置好的网络索引返回  
        // 连接配置好的指定ID的网络
        return mWifiManager.enableNetwork(wifiId,
                true);
    }

    public void startScan() {
        mWifiManager.startScan();
        // 得到扫描结果  
        mWifiList = mWifiManager.getScanResults();
        Set<ScanResult> set = new HashSet<ScanResult>();
        set.addAll(mWifiList);
        mWifiList.clear();
        mWifiList.addAll(set);
        // 得到配置好的网络连接
        mWifiConfiguration = mWifiManager.getConfiguredNetworks();
    }

    // 得到网络列表  
    public List<ScanResult> getWifiList() {
        return mWifiList;
    }

    // 查看扫描结果  
    public StringBuilder lookUpScan() {
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < mWifiList.size(); i++) {
            stringBuilder
                    .append("Index_" + new Integer(i + 1).toString() + ":");
            // 将ScanResult信息转换成一个字符串包  
            // 其中把包括：BSSID、SSID、capabilities、frequency、level  
            stringBuilder.append((mWifiList.get(i)).toString());
            stringBuilder.append("/n");
        }
        return stringBuilder;
    }

    // 得到MAC地址  
    public String getMacAddress() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getMacAddress();
    }

    // 得到接入点的BSSID  
    public String getBSSID() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.getBSSID();
    }

    // 得到IP地址  
    public int getIPAddress() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getIpAddress();
    }

    // 得到连接的ID  
    public int getNetworkId() {
        return (mWifiInfo == null) ? 0 : mWifiInfo.getNetworkId();
    }

    // 得到WifiInfo的所有信息包  
    public String getWifiInfo() {
        return (mWifiInfo == null) ? "NULL" : mWifiInfo.toString();
    }

    // 添加一个网络并连接  
    public void addNetwork(WifiConfiguration wcg) {
        int wcgID = mWifiManager.addNetwork(wcg);
        boolean b = mWifiManager.enableNetwork(wcgID, true);
        System.out.println("a--" + wcgID);
        System.out.println("b--" + b);
    }

    // 断开指定ID的网络  
    public void disconnectWifi(int netId) {
        mWifiManager.disableNetwork(netId);
        mWifiManager.disconnect();
    }

//然后是一个实际应用方法，只验证过没有密码的情况：

    public WifiConfiguration CreateWifiInfo(String SSID, String Password, int Type) {
        WifiConfiguration config = new WifiConfiguration();
        config.allowedAuthAlgorithms.clear();
        config.allowedGroupCiphers.clear();
        config.allowedKeyManagement.clear();
        config.allowedPairwiseCiphers.clear();
        config.allowedProtocols.clear();
        config.SSID = "\"" + SSID + "\"";

        WifiConfiguration tempConfig = this.IsExsits(SSID);
        if (tempConfig != null) {
            mWifiManager.removeNetwork(tempConfig.networkId);
        }

        if (Type == 1) //没有密码的情况
        {
            config.wepKeys[0] = "";
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 2) //WEP加密的情况
        {
            config.hiddenSSID = true;
            config.wepKeys[0] = "\"" + Password + "\"";
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
            config.wepTxKeyIndex = 0;
        }
        if (Type == 3) //WPA加密的情况
        {
            config.preSharedKey = "\"" + Password + "\"";
            config.hiddenSSID = true;
            config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
            config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
            //config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
            config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
            config.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
            config.status = WifiConfiguration.Status.ENABLED;
        }
        return config;
    }

    private WifiConfiguration IsExsits(String SSID) {
        List<WifiConfiguration> existingConfigs = mWifiManager.getConfiguredNetworks();
        for (WifiConfiguration existingConfig : existingConfigs) {
            if (existingConfig.SSID.equals("\"" + SSID + "\"")) {
                return existingConfig;
            }
        }
        return null;
    }

    //判定指定WIFI是否已经配置好,依据WIFI的地址BSSID,返回NetId
    public int IsConfiguration(String SSID) {
        Log.i("IsConfiguration", String.valueOf(mWifiConfiguration.size()));
        String convertSSID = "\""+SSID+"\"";
        for (int i = 0; i < mWifiConfiguration.size(); i++) {
            Log.i(mWifiConfiguration.get(i).SSID, String.valueOf(mWifiConfiguration.get(i).networkId));
            if (mWifiConfiguration.get(i).SSID.equals(convertSSID)) {//地址相同
                return mWifiConfiguration.get(i).networkId;
            }
        }
        return -1;
    }

    //添加指定WIFI的配置信息,原列表不存在此SSID
    public int AddWifiConfig(ScanResult scanResult, String pwd) {
        int wifiId = -1;
        Log.i("AddWifiConfig", "equals");
        int netID = IsConfiguration(scanResult.SSID);
        if (netID > 0)
            return netID;
        WifiConfiguration wifiCong = new WifiConfiguration();
        wifiCong.SSID = "\"" + scanResult.SSID + "\"";//\"转义字符，代表"
        wifiCong.preSharedKey = "\"" + pwd + "\"";//WPA-PSK密码
        wifiCong.hiddenSSID = false;
        wifiCong.status = WifiConfiguration.Status.ENABLED;
        wifiId = mWifiManager.addNetwork(wifiCong);//将配置好的特定WIFI密码信息添加,添加完成后默认是不激活状态，成功返回ID，否则为-1
        if (wifiId != -1) {
            return wifiId;
        }
        return wifiId;
    }

    public boolean connectWifi(final ScanResult wifiScan, final String wifiPassword) {
        if (wifiPassword != null) {
            int netId = AddWifiConfig(wifiScan, wifiPassword);
            if (netId > 0) {
               return connectWifi(netId, wifiScan, wifiPassword);
            } else {
                Logger.d(TAG, "conntect to " + wifiScan.SSID + "failed");
            }
        }
        return false;
    }

    private boolean connectWifi(final int wifiId, final ScanResult wifiScan, final String wifiPassword) {
        if(wifiId >= mWifiConfiguration.size())
            startScan();
        return connectConfiguration(wifiId);
    }
}
